﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIWindow.Enums;
using UIWindow.Lucifer;
using UIWindow.Models;

namespace UIWindow.Domains
{
    public class PolymorphicEventManagement : IPolymorphicEventManagement
    {
        private List<ManagerModel> _taskList;
        private readonly static object _obj = new object();
        private static PolymorphicEventManagement _polymorphic;
        private PolymorphicEventManagement()
        {
            _taskList = new List<ManagerModel>();
        }

        public static PolymorphicEventManagement GetObject()
        {
            if (_polymorphic == null)
            {
                lock (_obj)
                {
                    if (_polymorphic == null) _polymorphic = new PolymorphicEventManagement();
                }
            }
            return _polymorphic;
        }

        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="action"></param>
        public void Subscribe(string name, TriggerType type, Action<object[]> action)
        {
            var model = _taskList.FirstOrDefault(x => x.Name == name);
            if (model == null) _taskList.Add(new ManagerModel() { Name = name, TaskEvent = action, Type = type });
            else throw new Exception("不可重复添加相同的任务");
        }

        /// <summary>
        /// 发布任务
        /// </summary>
        /// <param name="name">任务名</param>
        /// <param name="value">PLC值</param>
        /// <param name="obj">参数</param>
        public void Publish(string name, object value, object[] obj)
        {
            var model = _taskList.FirstOrDefault(x => x.Name == name);
            if (model != null)
            {
                int count = 0;
                switch (model.Type)
                {
                    case TriggerType.OneToZero:
                        count = (ushort)value;
                        if (value != model.Value && count == 0) model.TaskEvent.Invoke(obj);
                        break;
                    case TriggerType.ZeroToOne:
                        count = (ushort)value;
                        if (value != model.Value && count == 1) model.TaskEvent.Invoke(obj);
                        break;
                    case TriggerType.Variety:
                        if (value != model.Value) model.TaskEvent.Invoke(obj);
                        break;
                    case TriggerType.Boolean:
                        bool bl = (bool)value;
                        if (value != model.Value && bl) model.TaskEvent.Invoke(obj);
                        break;
                    default:
                        break;
                }
                model.Value = value;
            }
        }
    }
}
